﻿using System;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;

using System.ComponentModel.Composition;
using EnergyService_CSharp;
using System.Windows.Forms;

namespace PachubePlugin
{
    [Export(typeof(IEnergyMonitorPlugin))]
    public class PachubePlugin : IEnergyMonitorPlugin
    {
        string apiKey;
        string feedId;
        string feedUrl = "http://www.pachube.com/api/";
        string webHeader = "X-PachubeApiKey";

        double pachubeEnergy = 0;
        double pachubeTemp = 0;
        int pachubeReadings = 0;
        double pachubeInterval = 1;
        DateTime pachubeLastUpload = DateTime.MinValue;

        #region IEnergyMonitorPlugin Members

        string IEnergyMonitorPlugin.Name
        {
            get { return "PachubePlugin"; }
        }

        string IEnergyMonitorPlugin.Description
        {
            get { return "Post your reading data to Pachube streams"; }
        }

        bool IEnergyMonitorPlugin.Enabled
        {
            get { return bool.Parse(GetSetting("pachubeplugin_enabled", "false")); }
        }

        bool IEnergyMonitorPlugin.Init()
        {
            apiKey = GetSetting("pachubeplugin_apikey", "your_api_key");
            feedId = GetSetting("pachubeplugin_feedid", "your_feed_id");
            pachubeInterval = double.Parse(GetSetting("pachubeplugin_interval", "1"));
            feedUrl += (feedId + ".csv");
            return true;
        }

        bool IEnergyMonitorPlugin.Notify(EnergyReading rdg)
        {
            pachubeEnergy += rdg.Energy;
            pachubeTemp += rdg.Temperature;
            pachubeReadings++;

            if (pachubeLastUpload.AddMinutes(pachubeInterval) < DateTime.Now)
            {
                try
                {
                    WebClient wc = new WebClient();
                    WebHeaderCollection whc = new WebHeaderCollection();
                    whc.Add(webHeader, apiKey);
                    wc.Headers = whc;
                    string putData = (pachubeEnergy/pachubeReadings).ToString("N") + "," + (pachubeTemp/pachubeReadings).ToString();
                    wc.UploadString(feedUrl, "PUT", putData);
                    pachubeEnergy = 0;
                    pachubeTemp = 0;
                    pachubeReadings = 0;
                    pachubeLastUpload = DateTime.Now;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("PachubePosterPlugin Error : " + ex.ToString());
                }
            }
            return true;
        }

        bool IEnergyMonitorPlugin.DeInit()
        {
            return true;
        }

        NameValueCollection IEnergyMonitorPlugin.Configure(NameValueCollection current)
        {
            NameValueCollection retVal = null;

            frmConfig frm = new frmConfig(current);
            DialogResult dlg = frm.ShowDialog();

            if (DialogResult.OK == dlg)
            {
                retVal = new NameValueCollection();
                retVal.Add("pachubeplugin_enabled", frm.Enabled.ToString().ToLower());
                retVal.Add("pachubeplugin_apikey", frm.APIKey);
                retVal.Add("pachubeplugin_feedid", frm.FeedId);
                retVal.Add("pachubeplugin_interval", frm.Interval.ToString());
            }
            return retVal;
        }

        #endregion

        private string GetSetting(string key, string defaultValue)
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            string val = defaultValue;
            try
            {
                string v = appSettings.Get(key);
                if (null != v)
                {
                    val = v;
                }
            }
            catch
            {
                // just ignore
            }
            return val;
        }


    }
}
